class Solution {
public:
    int getNext(int x){
        int sum = 0;
        int d;
        while(x){
            d = x % 10;
            sum += d * d;
            x /= 10;
        }
        return sum;
    }
    bool isHappy(int n) {
        int p = n;
        int q = n;
        while(q != 1){
            p = getNext(p);
            q = getNext(getNext(q));
            if(p == q && p != 1) return false; 
        }
        return true;
    }
};